import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '../utils/token-utils'
import userInfoApi, { type UserInfoFun } from '../api/userInfo'
import { showSuccessToast, showFailToast } from 'vant'
import router from "@/router"

interface UserInfoState {
  token: string,
  userInfoData: UserInfoFun,
  loginFrom: {
    phone: string,
    password: string,
  }
}

// 个人信息
const baseReqUserInfoModel = (): UserInfoFun => ({
  id: undefined,
  loginName: "",
  nickName: "",
  passwd: "",
  name: "",
  phoneNum: "",
  email: "",
  headImg: "",
  userLevel: "",
  status: undefined,
  birthday: null,
  gender: null,
  createTime: "",
  operateTime: null,
  openId: null
})





export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfoData: baseReqUserInfoModel(),
    loginFrom: {
      phone: '13700000000',
      password: '111111'
    },

  }),

  actions: {
    //登录
    async login(phone: string, password: string) {
      try {
        let result = await userInfoApi.login({ phone, password })
        setToken(result.token)
        this.token = result.token
        showSuccessToast('登录成功')
      } catch (error) {
        showFailToast('登陆失败')
        return Promise.reject(error)
      }
    },
    // 获得用户信息
    async userInfo() {
      try {
        let result = await userInfoApi.reqUserInfo()
        // console.log('result', result);
        // 存储个人信息
        this.userInfoData = result
      } catch (error) {
        showFailToast('获取个人信息失败');
        return Promise.reject(error)
      }
    },

    // 退出账号,清空数据
    async logout() {
      try {
        await userInfoApi.logout()
        // 删除local中的token
        removeToken()
        // 重置用户的mutation
        this.token = '',
          // 初始化用户数据
          this.userInfoData = baseReqUserInfoModel()
        showSuccessToast('退出账号成功')
      } catch (error) {
        showFailToast('退出账号失败')
        return Promise.reject(error)
      }
    },

    // 登录后跳转页面
    // async getLogin() {
    //   try {
    //     this.login(this.loginFrom.phone, this.loginFrom.password)
    //     // 跳转到主页
    //     router.push({ path: '/' })
    //   } catch (error) { }
    // }

    //  async getLogin(url: string) {
    //   try {
    //     this.login(this.loginFrom.phone,this.loginFrom.password )
    //     // 跳转到主页
    //     router.push({ path: url })
    //   } catch (error) {}
    // }

  }

})

export default useUserInfoStore